package com.hundsun.cprs.yyt.service.scheduler;

import com.hundsun.cprs.yyt.common.enums.EnumAreaCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.order.service.OrderService;
import com.hundsun.cprs.yyt.service.report.domain.DaliyClinchSum;
import com.hundsun.cprs.yyt.service.report.service.DaliyClinchSumService;
import com.hundsun.cprs.yyt.util.DateUtil;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;

@Service("daliyClinchSumQuartzService")
public class DaliyClinchSumQuartzService implements Serializable {

    Logger log = Logger.getLogger(getClass());

    @Autowired
    private DaliyClinchSumService daliyClinchSumService;

    public void daliyClinchSum() {
        try {
            log.info("日报表统计开始");
            Date PreDay = DateUtil.getPreviousDay(new Date(),1);
            Date startTime = DateUtil.getBeginOfDay(PreDay);
            Date endTime = DateUtil.getEndOfDay(PreDay);
            //1.获取零售区日成交汇总数据
            DaliyClinchSum retailDaliyClinchSum = daliyClinchSumService.getDaliyClinchSumFromArea(EnumAreaCode.RETAIL_AREA.getCode(),startTime,endTime);
            if (retailDaliyClinchSum != null){
                retailDaliyClinchSum.setAreaCode(EnumAreaCode.RETAIL_AREA.getCode());
            }else{
                //当日成交汇总数据为空，则新增默认数据
                retailDaliyClinchSum = new DaliyClinchSum();
                fillDefaultValue(retailDaliyClinchSum,EnumAreaCode.RETAIL_AREA.getCode(),PreDay);
            }
            //2.零售区日成交汇总数据落库
            daliyClinchSumService.add(retailDaliyClinchSum);

            //3.获取批发区日成交汇总数据
            DaliyClinchSum wholesaleDaliyClinchSum = daliyClinchSumService.getDaliyClinchSumFromArea(EnumAreaCode.WHOLESALE_AREA.getCode(),startTime,endTime);
            if (wholesaleDaliyClinchSum != null){
                wholesaleDaliyClinchSum.setAreaCode(EnumAreaCode.WHOLESALE_AREA.getCode());
            }else{
                //当日成交汇总数据为空，则新增默认数据
                wholesaleDaliyClinchSum = new DaliyClinchSum();
                fillDefaultValue(wholesaleDaliyClinchSum,EnumAreaCode.WHOLESALE_AREA.getCode(),PreDay);
            }
            //4.批发区日成交汇总数据落库
            daliyClinchSumService.add(wholesaleDaliyClinchSum);
            log.info("日报表统计结束");
        } catch (ServiceCodeException e) {
            log.error("日统计成交报表出错。", e);
        } catch (Exception e) {
            log.error("日统计成交报表出错。", e);
        }

    }

    public void fillDefaultValue(DaliyClinchSum daliyClinchSum,String areaCode,Date preday){
        daliyClinchSum.setAreaCode(areaCode);
        daliyClinchSum.setClinchAmountSum(0L);
        daliyClinchSum.setClinchMoneySum(0L);
        daliyClinchSum.setRewardMoneySum(0L);
        daliyClinchSum.setStatTime(preday);
    }
}